package mi.payment.transaction.sale.code;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import lainey.ui.dialog.IconHintDialog;
import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.admin.pay88.IPay88Wallet;
import mi.payment.admin.pay88.WebServiceApi;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.AccountType;
import mi.payment.constants.Params;
import mi.payment.db.PayDetailModel;
import mi.payment.db.dao.PayDetail;
import mi.payment.transaction.AutoFinishActivity;
import mi.payment.utils.CodeUtil;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.UIUtils;
import sunmi.payment.L3.L3BroadcastHelper;
import sunmi.payment.L3.L3ErrorCode;

public class CodeActivity extends AutoFinishActivity {

    private TextView mTvError;
    private ImageView mIvIcon;
    private ImageView mIvGenerateCode;

    private String mAmount;
    private IPay88Wallet mIPay88Wallet;

    private TradeData mTradeData;
    private PayDetail mPayDetail;

    private IconHintDialog mIconHintDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_avtivity_generate_code);
        setDelayed(120 * 1000);
        initView();
        initData();
        requestGenerateCode();
    }

    @Override
    protected void onResume() {
        super.onResume();
        UIUtils.screenMonopoly(1);
        // 将屏幕亮度设置到最亮，退出界面后还原亮度
        UIUtils.setLight(this, 255);
    }

    @Override
    public void onBackPressed() {
        showIconHintDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Params.sL3Params == null) {
            UIUtils.screenMonopoly(-1);
        }
    }

    private void initView() {
        Intent intent = getIntent();
        mAmount = intent.getStringExtra("amount");
        mIPay88Wallet = (IPay88Wallet) intent.getSerializableExtra("wallet");

        TitleView titleView = findViewById(R.id.title_view);
        titleView.setCenterText(R.string.consume);
        titleView.setLeftImageOnClickListener(
                v -> onBackPressed()
        );

        mIvIcon = findViewById(R.id.iv_logo);
        mTvError = findViewById(R.id.tv_error);
        mIvGenerateCode = findViewById(R.id.iv_code);
        TextView tvAmount = findViewById(R.id.tv_amount);

        mTvError.setVisibility(View.GONE);
        mIvIcon.setVisibility(View.GONE);
        mIvGenerateCode.setVisibility(View.GONE);

        String str = mIPay88Wallet.currency + ": " + mAmount;
        tvAmount.setText(str);
    }

    private void initData() {
        mTradeData = Params.newTradeData();
        mPayDetail = mTradeData.getPayDetail();
        mPayDetail.qrCodeScanModel = 2; // 设置交易类型:被扫
        mPayDetail.currency = mIPay88Wallet.currency;
        mPayDetail.accountType = AccountType.OA.getValue();
        mPayDetail.amount = MoneyUtils.stringMoney2LongCent(mAmount);

        // L3自定义订单号赋值
        if (Params.sL3Params != null) {
            mPayDetail.customOrderNo = Params.sL3Params.transId;
        }

        mPayDetail.transType = "UP";
        try {
            mPayDetail.transPlatform = Integer.parseInt(mIPay88Wallet.userPaymentID);
        } catch (Exception e) {
            mPayDetail.transPlatform = 1;
        }
    }

    private void requestGenerateCode() {
        // 消费
        mTradeData.getPayDetail().setTransactionType(1);
        showLoadingDialog(R.string.load_connecting);
        executeTask(
                () -> {
                    try {
                        TradeData tradeData = WebServiceApi.getInstance().saleTransaction(mTradeData, false);
                        PayDetail resPay = tradeData.getPayDetail();
                        String answerCode = resPay.tradeAnswerCode;
                        boolean equals = TextUtils.equals(answerCode, "00");
                        runOnUI(
                                () -> {
                                    if (equals) {
                                        PayDetailModel.getInstance().insert(resPay);

                                        Bitmap bitmap = CodeUtil.createCodeBitmap(resPay.payQRCode, 210, 210);
                                        mIvIcon.setVisibility(View.VISIBLE);
                                        mIvGenerateCode.setVisibility(View.VISIBLE);
                                        mIvIcon.setImageResource(mIPay88Wallet.iconResId);
                                        mIvGenerateCode.setImageBitmap(bitmap);
                                    } else {
                                        mTvError.setVisibility(View.VISIBLE);
                                        String error = getString(R.string.error_generate_code) + ": " + resPay.tradeResultDes;
                                        mTvError.setText(error);
                                    }
                                }
                        );
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUI(
                                () -> {
                                    mTvError.setVisibility(View.VISIBLE);
                                    String error = getString(R.string.error_generate_code);
                                    mTvError.setText(error);
                                }
                        );
                    } finally {
                        dismissLoadingDialog();
                    }
                }
        );
    }

    private void showIconHintDialog() {
        if (mIconHintDialog == null) {
            mIconHintDialog = new IconHintDialog(this);
            mIconHintDialog.setRightText(R.string.ok);
            mIconHintDialog.setLeftText(R.string.cancel);
            mIconHintDialog.setMessage(R.string.error_generate_code_warn);
            mIconHintDialog.setIconResource(R.drawable.state_warning);
            mIconHintDialog.setLeftOnClickListener(
                    v -> dismissIconHintDialog()
            );
            mIconHintDialog.setRightOnClickListener(
                    v -> {
                        dismissIconHintDialog();
                        L3BroadcastHelper.sendResultBroadcast(mContext, false, L3ErrorCode.ERROR_TRADE_CANCEL, mPayDetail);
                        finish();
                    }
            );
            mIconHintDialog.setCancelable(true);
            mIconHintDialog.setCanceledOnTouchOutside(true);
        }
        try {
            mIconHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissIconHintDialog() {
        if (mIconHintDialog != null) {
            try {
                mIconHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void startAction(Context context, String amount, int platform) {
        Intent intent = new Intent(context, CodeActivity.class);
        intent.putExtra("amount", amount);
        intent.putExtra("platform", platform);
        context.startActivity(intent);
    }

    public static void startAction(Context context, String amount, IPay88Wallet wallet) {
        Intent intent = new Intent(context, CodeActivity.class);
        intent.putExtra("amount", amount);
        intent.putExtra("wallet", wallet);
        context.startActivity(intent);
    }


}
